package uefs.springboot.rabbitmq.a1consumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import user.springboot.rabbitmq.a0base.RabbitMqUtil;

/*
1、声明队列
2、创建连接
3、创建通道
4、通道声明队列
5、重写消息消费方法
6、执行消息方法
*/
public class A1ConsumerWorkGueues {

	private static void workConsumer() throws IOException, TimeoutException {
		Connection connection = RabbitMqUtil.connectionGet();
		Channel channel = connection.createChannel();
		//通道绑定队列
		channel.queueDeclare(RabbitMqUtil.WORK_QUEUE, true, false, false, null);//通道绑定邮件队列

		//String consumerTag, Envelope envelope, BasicProperties properties, byte[] body
		DefaultConsumer consumer = new DefaultConsumer(channel) {
			/**
			  * 消费者接收消息调用此方法
			  * @param consumerTag 消费者的标签，在channel.basicConsume()去指定
			  * @param envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志
			    (收到消息失败后是否需要重新发送)
			  * @param properties
			  * @param body
			  * @throws IOException
			 * String consumerTag, Envelope envelope, BasicProperties properties, byte[] body
			 */
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				//交换机
				String exchange = envelope.getExchange();
				//路由key
				String routingKey = envelope.getRoutingKey();
				envelope.getDeliveryTag();
				String msg = new String(body, "utf-8");
				System.out.println("mq收到的消息是：" + msg);
			}

		};
		System.out.println("消费者启动成功！");
		channel.basicConsume(RabbitMqUtil.WORK_QUEUE, true, consumer);

		RabbitMqUtil.resourceClose(channel);
		RabbitMqUtil.resourceClose(connection);
	}

	public static void main(String[] args) throws IOException, TimeoutException {
		A1ConsumerWorkGueues.workConsumer();
	}
}